package co.fitstart.admin.web.controller.user.agent;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;

import co.fitstart.admin.service.AgentService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.entity.order.Order;
import co.fitstart.entity.user.agent.Agent;
import co.fitstart.entity.user.agent.AgentDiscount;
import co.fitstart.entity.user.agent.AgentRecord;
import co.fitstart.entity.user.agent.DiscountType;

@Controller
@RequestMapping("/agents/{agentId}")
@MenuSetting("menu-user")
public class OnlineAgentViewController {
    
private static final Logger logger = LoggerFactory.getLogger(OnlineAgentViewController.class);
    
    @Autowired
    private AgentService agentService;
    
    /**
     * 
     * @param agentId
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public ModelAndView info(@PathVariable("agentId") Long agentId) {
        ModelAndView modelAndView = new ModelAndView("user/agent/agent-user-info");
        
        Agent agent = agentService.loadAgent(agentId);
        modelAndView.addObject("agent", agent);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param agentId
     * @return
     */
    @RequestMapping(value = "/order", method = RequestMethod.GET)
    public ModelAndView agentOrder(@PathVariable("agentId") Long agentId) {
        ModelAndView modelAndView = new ModelAndView("user/agent/agent-order-view");
        
        Agent agent = agentService.loadAgent(agentId);
        modelAndView.addObject("agent", agent);
        
        List<Order> orders = agentService.listAgentOrder(agent);
        modelAndView.addObject("orders", orders);
        
        return modelAndView;
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/agent-discounts/create", method = RequestMethod.GET)
    public ModelAndView createDiscount(@PathVariable("agentId") Long agentId) {
        ModelAndView modelAndView = new ModelAndView("user/agent/agent-discount-create");
        
        Agent agent = agentService.loadAgent(agentId);
        modelAndView.addObject("agent", agent);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param agentId
     * @param discountType
     * @param payment
     * @param discount
     * @param commission
     * @return
     */
    @RequestMapping(value = "/agent-discounts", method = RequestMethod.POST)
    public @ResponseBody String onCreateDiscount(@PathVariable("agentId") Long agentId,
                                                 @RequestParam("discountType") String discountType,
                                                 @RequestParam("payment") String payment,
                                                 @RequestParam("discount") String discount,
                                                 @RequestParam("commission") String commission) {
        Result result = new Result();
        
        try {
            
            Agent agent = agentService.loadAgent(agentId);
            
            DiscountType type = DiscountType.aliasOf(discountType);
            if(type.isPayment()) {
                agentService.createAgentDiscount(agent, type, payment, commission);
            } else if(type.isDiscount()){
                agentService.createAgentDiscount(agent, type, discount, commission);
            }
            
            result.success().message("创建优惠成功");
            
        } catch (BusinessException e) {
            
            result.fail().message(e.getMessage());
            
        } catch (Exception e) {
            
            logger.error("onCreate() - ", e);
            result.fail().message("创建优惠失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/agent-discounts/{agentDiscountId}/delete", method = RequestMethod.GET)
    public ModelAndView deleteDiscount(@PathVariable("agentId") Long agentId,
                                       @PathVariable("agentDiscountId") Long agentDiscountId) {
        ModelAndView modelAndView = new ModelAndView("user/agent/agent-discount-delete");
        
        modelAndView.addObject("agentId", agentId);
        modelAndView.addObject("agentDiscountId", agentDiscountId);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param agent
     * @param discountOffer
     * @param commission
     * @param agentDiscount
     * @param userDiscounts
     * @return
     */
    @RequestMapping(value = "/agent-discounts/{agentDiscountId}", method = RequestMethod.DELETE)
    public @ResponseBody String onDeleteDiscount(@Preloading("id") AgentDiscount agentDiscount) {
        Result result = new Result();
        
        try {
            
            agentService.deleteAgentDiscount(agentDiscount);
            
            result.success().message("删除优惠成功");
            
        } catch (BusinessException e) {
            
            result.fail().message(e.getMessage());
            
        } catch (Exception e) {
            
            logger.error("onDeleteDiscount() - ", e);
            result.fail().message("删除优惠失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param agentId
     * @return
     */
    @RequestMapping(value = "/withdrawals", method = RequestMethod.GET)
    public ModelAndView withdrawal(@PathVariable("agentId") Long agentId, Page page, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("user/agent/agent-user-record");
        
        Agent agent = agentService.loadAgent(agentId);
        modelAndView.addObject("agent", agent);
        
        List<AgentRecord> agentRecords = agentService.listAgentRecord(agent, page);
        modelAndView.addObject("agentRecords", agentRecords);
        
        modelAndView.addObject("page", page);
        
        modelAndView.addObject("refer", "list");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
    }
    
    /**
     * 
     * @param agentId
     * @param withdrawalId
     * @return
     */
    @RequestMapping(value = "/agent-records/{agentRecordId}/pay", method = RequestMethod.GET)
    public ModelAndView pay(@PathVariable("agentId") Long agentId,
                            @PathVariable("agentRecordId") Long agentRecordId) {
        ModelAndView modelAndView = new ModelAndView("user/agent/agent-record-pay");
        
        modelAndView.addObject("agentId", agentId);
        modelAndView.addObject("agentRecordId", agentRecordId);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param agentId
     * @param agentRecordId
     * @return
     */
    @RequestMapping(value = "/agent-records/{agentRecordId}/pay", method = RequestMethod.PATCH)
    public @ResponseBody String onPay(@PathVariable("agentId") Long agentId,
                                      @PathVariable("agentRecordId") Long agentRecordId) {
        Result result = new Result();
        
        try {
            
            Agent agent = agentService.loadAgent(agentId);
            AgentRecord agentRecord = agentService.loadAgentRecord(agentRecordId);
            
            agentService.pay(agent, agentRecord);
            
            result.success().message("代言人打款成功");
            
        } catch (Exception e) {
            
            logger.error("onPay() - ", e);
            result.fail().message("代言人打款失败");
        }
        
        return JsonUtils.toJsonString(result);
    }

}
